from enum import Enum
from typing import Optional

import uvicorn
from fastapi import FastAPI
from fastapi.openapi.docs import get_swagger_ui_html
from pydantic import BaseModel
from starlette.staticfiles import StaticFiles

# 创建 FastAPI 应用实例，并把默认的/docs请求禁用
# debug表示是否开启调试模式，默认是False
app = FastAPI(docs_url=None,debug=True)
app.mount("/static", StaticFiles(directory="../static"), name="static")    # 静态文件

@app.get("/docs", include_in_schema=False)
def custom_swagger_ui():
    return get_swagger_ui_html(
        openapi_url = "/openapi.json",
        title = "Swagger UI for FastAPI",
        swagger_js_url="/static/swagger-ui-bundle.min.js",
        swagger_css_url="/static/swagger-ui.min.css"
    )

# 自定义枚举
class Gender(str, Enum):
    MALE = "male"
    FEMALE = "female"

# 定义数据模型
class UserModel(BaseModel):
    username: str
    # desc 这个字段可以为空
    desc: Optional[str] = None
    active: Optional[bool] = True
    gender: Gender

@app.post("/user")
async def create_user(user: UserModel):
    user_dict = user.model_dump()       # 这里返回的是python中的dict
    print("user_dict:", user_dict)
    user_json = user.model_dump_json()  # 这里返回的是json字符串
    print("user_json:", user_json)
    # 响应user会自动转为json格式数据
    # 直接返回user:FastAPI会自动调用模型的model_dump()方法并把结果转为json响应
    # return user
    # 我们也可以返回user_dict(我们根据模型转回来的dict)
    # 返回 user.model_dump()：手动完成模型到字典的转换
    return user_dict

@app.put("/user/{user_id}")
async def update_user(user_id: int, user: UserModel):
    user_dict = user.model_dump()
    # 更新模型数据的dict，把user_id写进去
    user_dict.update({"user_id": user_id})
    return user_dict


if __name__ == '__main__':
    uvicorn.run("main:app", host="127.0.0.1", port=8003, reload=True)